var express = require("express");
var router = express.Router();
const Result = require("../../utils/result");
const goodsServices = require("../services/goods");
var fs = require("fs");
const multer = require("multer");
const upload = multer({ dest: "public/images/admin/" }); // 文件储存路径

// 上传商品图片
router.post("/uploadImg", upload.single("file"), function (req, res, next) {
  try {
    let file = req.file;
    const oldPath = file.destination + file.filename;
    const type = file.mimetype.split("/")[1];
    const fileFullname = file.filename + "." + type;
    const newPath = "public/images/admin/" + fileFullname;
    // 修改文件名，为文件加上后缀
    fs.rename(oldPath, newPath, function (err) {
      if (err) {
        throw err;
      }
    });
    // 返回静态资源地址
    const imageUrl = "http://localhost:8080/images/admin/" + fileFullname;
    res.json(Result.success({ imageUrl }));
  } catch (error) {
    res.json(Result.fail(error));
  }
});

//添加商品
router.post('/goods',async function (req, res){
  const {goods} = req.body;
  await goodsServices.addGoods(goods);
  res.json(Result.success());
});

//获取一条商品
router.get('/goods/:id',async function (req, res){
  const id = req.params.id;
  const goods = await goodsServices.getGoods(id);
  res.json(Result.success({goods}));
});


//更新一条商品
router.put('/goods/:id',async function (req, res){
  const id = req.params.id;
  const goods = req.body.goods;
  await goodsServices.updateGoods(id,goods);
  res.json(Result.success());
});

//删除一条商品
router.delete('/goods/:id',async function (req, res){
  const id = req.params.id;
  await goodsServices.deleteGoods(id);
  res.json(Result.success());
});

//获取商品列表
router.get("/getList", async function (req, res) {
  const { keyword, page, size } = req.query;
  const { rows, count } = await goodsServices.getGoodsList(keyword, page, size);
  res.json(Result.success({ goodsArr: rows, count }));
});



module.exports = router;
